#pragma once
#include<iostream>
#include<string>
#include"Connection.hpp"
#include "Common.hpp"
#include "Log.hpp"
#include<cerrno>
#include"HandlerConnection.hpp"

class Accepter
{
    
public:
    Accepter()
    {

    }
    void AccepterConnection(Connection *conn)
    {
        std::cout<<"开始监听了！！！\n";
        errno=0;
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            int sockfd=::accept(conn->SockFd(),(struct sockaddr*)&peer,&len);
            if(sockfd>0)
            {
                lg.LogMessage(Info,"get a new link,sockfd is : %d",sockfd);
                SetNonBlock(sockfd);
                auto recver=std::bind(&HandlerConnection::Recver,std::placeholders::_1);
                auto sender = std::bind(&HandlerConnection::Sender, std::placeholders::_1);
                auto excepter = std::bind(&HandlerConnection::excepter, std::placeholders::_1);
                Connection *normal_conn=ConnectionFactory::BuildNormalConnectiom(sockfd,recver,sender,excepter,EPOLLIN|EPOLLET,conn->_R);
                conn->_R->AddConnection(normal_conn);
                // break;
            }
            else
            {
                if (errno == EAGAIN)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                {
                    lg.LogMessage(Warning, "get a new link error\n");
                    break;
                }
            }
        }
    }
    ~Accepter()
    {

    }
    
};